package com.ddshuai.easy;

import java.util.Stack;

/**
 * 编写一个函数来查找字符串数组中最长的公共前缀字符串。
 *
 * @author admin
 */
public class LongestCommonPrefix {

    private static String longestCommonPrefix(String[] strings) {
        if (strings == null || strings.length == 0) {
            return "";
        }

        if (strings.length == 1) {
            return strings[0];
        }

        Stack<String> stack = new Stack<>();
        String commmon = null;
        //先将字符串压入栈中
        for (String string : strings) {
            //存在null值肯定就没有公共前缀啦
            if (string == null){
                return "";
            }
            stack.push(string);
        }

        while (!stack.isEmpty()){
            if (commmon == null){
                commmon = stack.pop();
            }
            //说明已经没找到公共部分了
            if ("".equals(commmon)){
                break;
            }
            //获取公共部分
            char[] target = stack.pop().toCharArray();
            char[] result = commmon.toCharArray();
            StringBuilder temp = new StringBuilder();
            for (int i = 0; i < result.length ; i++) {
                if (target.length >= i+1){
                    if (target[i] != result[i]){
                        break;
                    }else {
                        temp.append(target[i]).append("");
                    }
                }
            }

            if ("".equals(temp.toString())){
                return "";
            }
            commmon = temp.toString();

        }
        return commmon;
    }

    public static void main(String[] args) {
        System.out.println(longestCommonPrefix(new String[]{"c","acc","ccc"}));
    }
}
